package com.yc.cinema.proxy;

import com.yc.cinema.designpatterm.proxy.saticpy.MusicTeacher;
import org.springframework.cglib.proxy.Enhancer;
import org.springframework.cglib.proxy.MethodInterceptor;
import org.springframework.cglib.proxy.MethodProxy;

import java.lang.reflect.Method;

/**
 * 基于继承+动态字节码技术
 * <p>
 * A 类
 * class B extends A {
 * public void test(){
 * sout ...
 * super.test();
 * sout ...
 * }
 * }
 *
 *    final 关键字会影响CGLIB的代理
 *
 */
public class CGLIBProxy {

    public static void main(String[] args) {
        MusicTeacher musicTeacher = new MusicTeacher();
        MusicTeacher mt = CGLIBProxy.proxy(musicTeacher);
        mt.teach();
    }

    public static <T> T proxy(T t) {
        Enhancer enhancer = new Enhancer();
        enhancer.setSuperclass(t.getClass());
        enhancer.setCallback(new MethodInterceptor() {
            @Override
            public Object intercept(Object o, Method method, Object[] objects,
                                    MethodProxy methodProxy) throws Throwable {
                System.out.println("开始代理...");
                System.out.println("教语文");
                Object ret = methodProxy.invoke(t, objects);
                System.out.println("代理结束...");
                return ret;
            }
        });
        return (T) enhancer.create();
    }

}
